﻿@page "/account/confirmemail"
@page "/account/confirmemail/{UserId}"
@using BlazorBoilerplate.Shared.Dto.Account

@layout LoginLayout
@inject NavigationManager navigationManager
@inject HttpClient Http
@inject AuthenticationStateProvider authStateProvider
@inject IMatToaster matToaster

<MatCard>
    <div class="logo">
        <img src="_content/BlazorBoilerplate.CommonUI/images/blazorboilerplate.svg" style="width:100px;" /><br />Blazor Boilerplate
        <br />
        <h4>New User Email Confirmation</h4>
    </div>
    <EditForm Model="@confirmEmailParameters" OnValidSubmit="@SendConfirmation">
        <DataAnnotationsValidator />
        <ValidationSummary />
        <fieldset>
            <div class="form-group">
                <MatTextField @bind-Value="@confirmEmailParameters.UserId" Label="UserId" Icon="person" IconTrailing="true" FullWidth="true" Required="true"></MatTextField>
            </div>
            <div class="form-group">
                <MatTextField @bind-Value="@confirmEmailParameters.Token" Label="Token" Icon="lock_outline" IconTrailing="true" FullWidth="true" Required="true"></MatTextField>
            </div>
            <div class="form-group d-flex justify-content-end">
                <MatButton Type="submit" Raised="true" Disabled="@disableConfirmButton">Send Confirmation</MatButton>
            </div>
        </fieldset>
    </EditForm>
</MatCard>

@code {
    ConfirmEmailDto confirmEmailParameters { get; set; } = new ConfirmEmailDto();
    bool disableConfirmButton = false;

    [Parameter]
    public string UserId { get; set; }

    protected override async Task OnInitializedAsync()
    {
        // Blazor does not have query string accessible parameters yet so a hack is needed. Token is too long for path parameter
        var absoluteUrl = navigationManager.Uri;
        var token = absoluteUrl.Substring(absoluteUrl.IndexOf("?token=") + 7);

        if (!string.IsNullOrEmpty(UserId) && !string.IsNullOrEmpty(token))
        {
            disableConfirmButton = true;
            confirmEmailParameters = new ConfirmEmailDto
            {
                Token = token,
                UserId = this.UserId
            };
            await SendConfirmation();
        }
    }

    async Task SendConfirmation()
    {
        try
        {
            await ((IdentityAuthenticationStateProvider)authStateProvider).ConfirmEmail(confirmEmailParameters);
            matToaster.Add("Account has been Approved and Activated", MatToastType.Success);
            //Todo Take user to their profile page to edit their profile.
            navigationManager.NavigateTo("/");
        }
        catch (Exception ex)
        {
            matToaster.Add(ex.Message, MatToastType.Danger, "Email Verification Failed");
        }
    }
}
